package cn.com.open.itembank.controller;

import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.dto.QuestionTypeDto;
import cn.com.open.itembank.dto.QuestionTypeManageDto;
import cn.com.open.itembank.dto.ReturnModel;
import cn.com.open.itembank.entity.QuestionType;
import cn.com.open.itembank.interceptor.Log;
import cn.com.open.itembank.service.QuestionTypeRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by lucky on 2017/8/14.
 */

/**
 * 题型控制器
 */
@RestController
@RequestMapping("/itembank")
public class QuestionTypeController extends BaseController {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(QuestionTypeController.class);

    @Autowired
    private QuestionTypeRemoteService service;

    //region 新增相关（Create：理论方法 HttpPost）

    //region 新增题型（内部）

    /**
     * 新增题型（内部）
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId the itembankId
     * @param model      the model
     */
    @Log(optType = "新增题型（内部）", optDescription = "新增题型（内部），参数：%s", keyName = "model")
    @RequestMapping(value = "/{itembankId}/questiontype", method = RequestMethod.POST)
    public void createQuestionType(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable(value = "itembankId") String itembankId,
                                   @RequestBody QuestionTypeDto model) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //调用服务层方法
        ReturnModel result = service.insert(itembankId, model);

        if (result.getCode() == GlobalConst.COURSE_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result.getCode() == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, result.getData(), result.getMessage(), result.getCode());
        }
    }

    //endregion

    //endregion

    //region 删除相关（Delete：理论方法 HttpDelete）

    //region 删除题型

    /**
     * 删除题型
     *
     * @param request        the request
     * @param response       the response
     * @param itembankId     题库id
     * @param questionTypeId 题型id
     */
    @Log(optType = "删除题型", optDescription = "删除题型，题型ID：%s", keyName = "questionTypeId")
    @RequestMapping(value = "/{itembankId}/questiontype/{questionTypeId}", method = RequestMethod.DELETE)
    public void deleteQuestionType(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable(value = "itembankId") String itembankId,
                                   @PathVariable(value = "questionTypeId") String questionTypeId) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (!isPermissionForItemBank(request, itembankId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        int result = service.delete(questionTypeId, itembankId);

        if (result == GlobalConst.COURSE_NOT_EXIST || result == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else if (result == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }

    //endregion

    //endregion

    //region 更新相关（Update：理论方法 HttpPut）

    //region 修改题型

    /**
     * 修改题型
     *
     * @param request        the request
     * @param response       the response
     * @param itembankId     题库ID
     * @param questionTypeId 题型ID
     * @param model          题型修改模型
     */
    @Log(optType = "修改题型", optDescription = "修改题型，ID：%s", keyName = "questionTypeId")
    @RequestMapping(value = "/{itembankId}/questiontype/{questionTypeId}", method = RequestMethod.PUT)
    public void updateQuestionType(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable(value = "itembankId") String itembankId,
                                   @PathVariable(value = "questionTypeId") String questionTypeId,
                                   @RequestBody QuestionTypeDto model) {

        if (!isPermissionForAppId(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        int result = service.update(questionTypeId, itembankId, model);

        if (result == GlobalConst.COURSE_NOT_EXIST || result == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (result == GlobalConst.DATA_EXIST) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
        } else {
            responseJson(request, response, "", "", result);
        }
    }

    //endregion

    //region 修改题型状态

    /**
     * 修改题型状态
     *
     * @param request        the request
     * @param response       the response
     * @param itembankId     题库id
     * @param questionTypeId the question type id
     */
    @Log(optType = "修改题型状态", optDescription = "修改题型状态，ID：%s", keyName = "questionTypeId")
    @RequestMapping(value = "/{itembankId}/questiontype/{questionTypeId}/status", method = RequestMethod.PUT)
    public void updateQuestionTypeStatus(HttpServletRequest request, HttpServletResponse response,
                                         @PathVariable(value = "itembankId") String itembankId,
                                         @PathVariable(value = "questionTypeId") String questionTypeId) {

        int result = service.changeStatus(questionTypeId, itembankId);

        if (result == GlobalConst.COURSE_NOT_EXIST || result == GlobalConst.DATA_FORMAT_ERROR || result == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (result == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, "", "", result);
        }
    }

    //endregion

    //endregion

    //region 查询相关（Retrieve：理论方法 HttpGet）

    //region 获取题型信息

    /**
     * 获取题型信息
     *
     * @param request        the request
     * @param response       the response
     * @param questionTypeId 题型id
     */
    @Log(optType = "获取题型信息", optDescription = "获取题型信息，题型ID：%s", keyName = "questionTypeId")
    @RequestMapping(value = "/{itembankId}/questiontype/{questionTypeId}", method = RequestMethod.GET)
    public void getQuestionType(HttpServletRequest request, HttpServletResponse response,
                                @PathVariable(value = "questionTypeId") String questionTypeId) {

        QuestionType model = service.getQuestionType(questionTypeId);
        if (model != null) {
            responseJson(request, response, model, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    //endregion

    //region 获取题型列表

    /**
     * 获取题型列表
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     * @param name       题型名称
     */
    @Log(optType = "获取题型列表", optDescription = "获取题型列表，题库ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}/questiontypelist", method = RequestMethod.GET)
    public void getQuestionTypeList(HttpServletRequest request, HttpServletResponse response,
                                    @PathVariable(value = "itembankId") String itembankId,
                                    @RequestParam(value = "name", defaultValue = "", required = false) String name) {

        List<QuestionTypeManageDto> model = service.getListByItemBankIdAndName(itembankId, name);

        if (!isPermissionForItemBank(request, itembankId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (model != null && !model.isEmpty()) {
            responseJson(request, response, model, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    //endregion

    //region 获取题型列表

    /**
     * 获取题型列表
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     */
    @Log(optType = "获取题型列表", optDescription = "获取题型列表，题库ID：%s", keyName = "itembankId")
    @RequestMapping(value = "/{itembankId}/questiontypes", method = RequestMethod.GET)
    public void getQuestionTypes(HttpServletRequest request, HttpServletResponse response,
                                 @PathVariable(value = "itembankId") String itembankId) {

        List<QuestionType> model = service.getListByItemBankId(itembankId);
        if (!isPermissionForItemBank(request, itembankId)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (model != null && !model.isEmpty()) {
            responseJson(request, response, model, "");
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    //endregion

    //endregion
}
